/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.dao;

import org.ipti.br.tag.entity.Actor;
import org.ipti.br.tag.entity.ActorSchedule;
import org.ipti.br.tag.entity.ActorSchedule_;
import org.ipti.br.tag.entity.Actor_;
import org.ipti.br.tag.entity.UnitySchedule;
import org.ipti.br.tag.entity.enums.Reference;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author israel
 */
@Stateless
public class ActorScheduleFacade extends AbstractFacade<ActorSchedule> {

    @PersistenceContext(unitName = "TAG2PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ActorScheduleFacade() {
        super(ActorSchedule.class);
    }

    @Override
    public void create(ActorSchedule actorSchedule) {
        getEntityManager().persist(actorSchedule);
    }

    @Override
    public void edit(ActorSchedule actorSchedule) {
        actorSchedule.setSerialNumber(null);

        getEntityManager().merge(actorSchedule);
    }

    public void editForSynchronization(ActorSchedule actorSchedule) {
        getEntityManager().merge(actorSchedule);
    }
    
    public ActorSchedule find(UnitySchedule unitySchedule, Actor actor) throws NoResultException{
        EntityManager em = getEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ActorSchedule> cq = cb.createQuery(ActorSchedule.class);
        Root<ActorSchedule> rt = cq.from(ActorSchedule.class);
        
        cq.where(
                    cb.equal(rt.get(ActorSchedule_.actor).get(Actor_.id), actor.getId()),
                    cb.equal(rt.get(ActorSchedule_.reference), Reference.UNITY_SCHEDULE),
                    cb.equal(rt.get(ActorSchedule_.referenceID), unitySchedule.getId())
                );
        
        ActorSchedule actorSchedule = null;
        try{
             actorSchedule =  em.createQuery(cq).getSingleResult();
        }catch(NoResultException nrex){}
        
        return actorSchedule != null ? actorSchedule : null;
    }
}
